<template>
  <div class="app-container">
    <el-alert
      title="商品审核管理"
      description="当前页面显示待审核的商品列表，您可以对商品进行审核操作。"
      type="info"
      :closable="false"
      style="margin-bottom: 20px; color: red"
    />
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品编号" prop="productSn">
        <el-input
          v-model="queryParams.productSn"
          placeholder="请输入商品编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['shangpin:approval:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shangpin:approval:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shangpin:approval:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['shangpin:approval:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="approvalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column label="商品名称" align="left" prop="productName" />
      <el-table-column label="商品编号" align="left" prop="productSn" />
      <el-table-column label="价格" align="left" prop="price" min-width="100">
        <template #default="scope">
          <span style="color: #f56c6c; font-weight: bold;">¥{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="left" prop="auditMessage" min-width="100">
        <template #default="scope">
          <span class="dian">·</span>
          <el-text type="danger" v-if="scope.row.auditMessage === '待审核'">待审核</el-text>
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" align="left" prop="shopName" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" min-width="200">
        <template #default="scope">
          <el-button link type="success" icon="Check" @click="handleApprove(scope.row)" v-hasPermi="['shangpin:approval:approve']">通过</el-button>
          <el-button link type="danger" icon="Close" @click="handleReject(scope.row)" v-hasPermi="['shangpin:approval:reject']">拒绝</el-button>
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['shangpin:approval:view']">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品审核对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="approvalRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="删除标志 1/0 删除/未删除" prop="deleteFlag">
          <el-input v-model="form.deleteFlag" placeholder="请输入删除标志 1/0 删除/未删除" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品编号" prop="productSn">
          <el-input v-model="form.productSn" placeholder="请输入商品编号" />
        </el-form-item>
        <el-form-item label="计量单位" prop="productUnit">
          <el-input v-model="form.productUnit" placeholder="请输入计量单位" />
        </el-form-item>
        <el-form-item label="商品详情" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品移动端详情" prop="mobileDescription">
          <el-input v-model="form.mobileDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品卖点" prop="sellingPoint">
          <el-input v-model="form.sellingPoint" placeholder="请输入商品卖点" />
        </el-form-item>
        <el-form-item label="销售价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入销售价格" />
        </el-form-item>
        <el-form-item label="成本价格" prop="costPrice">
          <el-input v-model="form.costPrice" placeholder="请输入成本价格" />
        </el-form-item>
        <el-form-item label="原价/市场价" prop="originalPrice">
          <el-input v-model="form.originalPrice" placeholder="请输入原价/市场价" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="已售数量" prop="soldNum">
          <el-input v-model="form.soldNum" placeholder="请输入已售数量" />
        </el-form-item>
        <el-form-item label="商品重量(kg)" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入商品重量(kg)" />
        </el-form-item>
        <el-form-item label="主图路径" prop="mainImage">
          <image-upload v-model="form.mainImage"/>
        </el-form-item>
        <el-form-item label="缩略图路径" prop="thumbnail">
          <el-input v-model="form.thumbnail" placeholder="请输入缩略图路径" />
        </el-form-item>
        <el-form-item label="商品视频" prop="productVideo">
          <file-upload v-model="form.productVideo"/>
        </el-form-item>
        <el-form-item label="商品相册" prop="imageGallery">
          <image-upload v-model="form.imageGallery"/>
        </el-form-item>
        <el-form-item label="是否推荐" prop="isRecommend">
          <el-input v-model="form.isRecommend" placeholder="请输入是否推荐" />
        </el-form-item>
        <el-form-item label="是否热销" prop="isHot">
          <el-input v-model="form.isHot" placeholder="请输入是否热销" />
        </el-form-item>
        <el-form-item label="是否新品" prop="isNew">
          <el-input v-model="form.isNew" placeholder="请输入是否新品" />
        </el-form-item>
        <el-form-item label="审核状态" prop="auditMessage">
          <el-input v-model="form.auditMessage" placeholder="请输入审核状态" />
        </el-form-item>
        <el-form-item label="商品类型ID" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入商品类型ID" />
        </el-form-item>
        <el-form-item label="品牌ID" prop="brandId">
          <el-input v-model="form.brandId" placeholder="请输入品牌ID" />
        </el-form-item>
        <el-form-item label="店铺ID" prop="shopId">
          <el-input v-model="form.shopId" placeholder="请输入店铺ID" />
        </el-form-item>
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="form.shopName" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="运费模板ID" prop="templateId">
          <el-input v-model="form.templateId" placeholder="请输入运费模板ID" />
        </el-form-item>
        <el-form-item label="商品参数" prop="productParams">
          <el-input v-model="form.productParams" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品规格" prop="specs">
          <el-input v-model="form.specs" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="评论数量" prop="commentNum">
          <el-input v-model="form.commentNum" placeholder="请输入评论数量" />
        </el-form-item>
        <el-form-item label="商品评分" prop="grade">
          <el-input v-model="form.grade" placeholder="请输入商品评分" />
        </el-form-item>
        <el-form-item label="是否自营" prop="isSelfOperated">
          <el-input v-model="form.isSelfOperated" placeholder="请输入是否自营" />
        </el-form-item>
        <el-divider content-position="center">商品分类信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddProductCategory">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteProductCategory">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="productCategoryList" :row-class-name="rowProductCategoryIndex" @selection-change="handleProductCategorySelectionChange" ref="productCategory">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="佣金比例(百分比)" prop="commissionRate" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.commissionRate" placeholder="请输入佣金比例(百分比)" />
            </template>
          </el-table-column>
          <el-table-column label="分类名称" prop="categoryName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.categoryName" placeholder="请输入分类名称" />
            </template>
          </el-table-column>
          <el-table-column label="状态:disabled-禁用,enabled-正常启用" prop="status" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.status" placeholder="请选择状态:disabled-禁用,enabled-正常启用">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Approval">
import { listApproval, getApproval, delApproval, addApproval, updateApproval } from "@/api/shangpin/approval"
import { useRouter} from "vue-router"

const router = useRouter()
const { proxy } = getCurrentInstance()

const approvalList = ref([])
const productCategoryList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedProductCategory = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productName: null,
    productSn: null,
    price: null,
    status: null,
    auditMessage: "待审核", // 默认只显示待审核状态的数据
    categoryId: null,
    brandId: null,
    shopId: null,
    shopName: null,
    templateId: null,
    productParams: null,
    specs: null,
    commentNum: null,
    grade: null,
    salesModel: null,
    isSelfOperated: null
  },
  rules: {
    productName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" }
    ],
    productSn: [
      { required: true, message: "商品编号不能为空", trigger: "blur" }
    ],
    price: [
      { required: true, message: "销售价格不能为空", trigger: "blur" }
    ],
    stock: [
      { required: true, message: "库存数量不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询商品审核列表 */
function getList() {
  loading.value = true
  listApproval(queryParams.value).then(response => {
    approvalList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    createBy: null,
    createTime: null,
    deleteFlag: null,
    updateBy: null,
    updateTime: null,
    productName: null,
    productSn: null,
    productUnit: null,
    description: null,
    mobileDescription: null,
    sellingPoint: null,
    price: null,
    costPrice: null,
    originalPrice: null,
    stock: null,
    soldNum: null,
    weight: null,
    mainImage: null,
    thumbnail: null,
    productVideo: null,
    imageGallery: null,
    status: null,
    isRecommend: null,
    isHot: null,
    isNew: null,
    auditStatus: null,
    auditMessage: null,
    categoryId: null,
    brandId: null,
    shopId: null,
    shopName: null,
    templateId: null,
    productParams: null,
    specs: null,
    commentNum: null,
    grade: null,
    salesModel: null,
    isSelfOperated: null
  }
  productCategoryList.value = []
  proxy.resetForm("approvalRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // 重置后保持审核状态为待审核
  queryParams.value.auditMessage = "待审核"
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商品审核"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getApproval(_id).then(response => {
    form.value = response.data
    productCategoryList.value = response.data.productCategoryList
    open.value = true
    title.value = "修改商品审核"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["approvalRef"].validate(valid => {
    if (valid) {
      form.value.productCategoryList = productCategoryList.value
      if (form.value.id != null) {
        updateApproval(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addApproval(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除商品审核编号为"' + _ids + '"的数据项？').then(function() {
    return delApproval(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 通过审核操作 */
function handleApprove(row) {
  const _id = row.id
  proxy.$modal.confirm('确认通过商品"' + row.productName + '"的审核？').then(function() {
    const updateData = {
      id: _id,
      auditMessage: "审核通过"
    }
    return updateApproval(updateData)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("审核通过成功")
  }).catch(() => {})
}

/** 拒绝审核操作 */
function handleReject(row) {
  const _id = row.id
  proxy.$modal.confirm('确认拒绝商品"' + row.productName + '"的审核？').then(function() {
    const updateData = {
      id: _id,
      auditMessage: "审核拒绝"
    }
    return updateApproval(updateData)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("审核拒绝成功")
  }).catch(() => {})
}

/** 查看详情操作 */
function handleView(row) {
  router.push({
    path: '/shangpin/approval/detail',
    query: { id: row.id }
  });
}

/** 商品分类序号 */
function rowProductCategoryIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 商品分类添加按钮操作 */
function handleAddProductCategory() {
  let obj = {}
  obj.commissionRate = ""
  obj.categoryName = ""
  obj.status = ""
  productCategoryList.value.push(obj)
}

/** 商品分类删除按钮操作 */
function handleDeleteProductCategory() {
  if (checkedProductCategory.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的商品分类数据")
  } else {
    const productCategorys = productCategoryList.value
    const checkedProductCategorys = checkedProductCategory.value
    productCategoryList.value = productCategorys.filter(function(item) {
      return checkedProductCategorys.indexOf(item.index) == -1
    })
  }
}

/** 复选框选中数据 */
function handleProductCategorySelectionChange(selection) {
  checkedProductCategory.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('shangpin/approval/export', {
    ...queryParams.value
  }, `approval_${new Date().getTime()}.xlsx`)
}

getList()
</script>
